package com.walleipt.ak47.services;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.walle.ak47.commons.utils.SpringContextHolder;
import com.walle.ak47.commons.utils.StringUtils;

public class DispatchApiServiceServlet extends HttpServlet
{
	private static final long serialVersionUID = 1L;
	private static final Logger LOG = LoggerFactory.getLogger( DispatchApiServiceServlet.class ) ;
	
	String  pakcageNamePrefix = "com.wallipt.ak47.services.";
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		try
		{
			String target = StringUtils.after(request.getRequestURI(), request.getServletPath())   ;
			// 查找指定处理请求的services
			if ( StringUtils.isBlank(target) ) return ;
			
			StringBuilder classAllName = new StringBuilder( pakcageNamePrefix ) ;
			String pathScopes[] = StringUtils.split( target, "/" ) ;
			for( int i=0; i<pathScopes.length; i++ )
			{
				if ( StringUtils.isBlank(pathScopes[i]) ) continue ;
				if ( i == (pathScopes.length-1) )
				{
					classAllName.append( StringUtils.toLowerCaseFirstOne(pathScopes[i]) ).append(".").append( StringUtils.toUpperCaseFirstOne( pathScopes[i] ) ) ;
				}
				else
				{
					classAllName.append( pathScopes[i] ).append(".") ;
				}
			}
			
			Map<String, ?> objMap = SpringContextHolder.getApplicationContext().getBeansOfType( Class.forName(classAllName.toString()) ) ;
			if ( objMap == null || objMap.size()!=1 ) return ;
			
			Object targetService = objMap.entrySet().iterator().next().getValue() ;
			if ( !(targetService instanceof ApiServices) ) return ;

			
			String result = null ;
						
			// 执行业务返回结果
			if ( StringUtils.isBlank(result) )
			{
				ApiServices services = (ApiServices)targetService ;
				services.process( request, response ) ;
			}
			
		}
		catch( Throwable err )
		{
			err.printStackTrace();
			LOG.error( "Error occured. {}", err.getMessage() ) ;
			return ;
		}
	}
   
}
